<template>
  <div id="BarChart" ref="barChart" class="bar-chart"></div>
</template>

<script>
import { barOptions, resizeChart } from "@/assets/js/echartOptions.js";
export default {
  name: "BarChart",
  props: {
    xAxis: {
      type: Array,
      default: () => {
        return [];
      },
    },
    yAxisName: {
      type: String,
      default: "",
    },
    datas: {
      type: Array,
      default: () => {
        return [];
      },
    },
    grid: {
      type: Object,
      default: () => {
        return {
          left: "5%",
          right: "7%",
          bottom: "8%",
          top: "18%",
          containLabel: true,
        };
      },
    },
    isClick: {
      type: Boolean,
      default: false,
    },
    rotate: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      barChart: null,
      options: null,
    };
  },
  watch: {
    xAxis(val) {
      this.options.xAxis = val;
      this.barChart.setOption(barOptions({ ...this.options }), true, true);
      this.barChart.resize();
    },
    datas: {
      handler(val, oldVal) {
        this.options.datas = val;
        this.barChart.setOption(barOptions({ ...this.options }), true, true);
        this.barChart.resize();
      },
      deep: true,
    },
  },
  mounted() {
    this.barChart = this.$echarts.init(this.$refs["barChart"]);
    this.options = {
      yAxisName: this.yAxisName,
      xAxis: this.xAxis,
      datas: this.datas,
      grid: this.grid,
      isClick: this.isClick,
      rotate: this.rotate

    };
    this.barChart.setOption(barOptions({ ...this.options }), true, true);

    this.barChart.on("click", (param) => {
      if (this.isClick) {
        this.$emit("clickFn", param);
      }
    });
    const that = this;
    // this.$refs.barChart.addEventListener('click', function (evt) { //这里直接使用的是未被echart实例的dom元素。
    //   let length = (that.xAxis.length + 1) * 3;
    //   let e = evt || window.event;
    //   let numall = e.target.clientWidth - 90 - 60;
    //   let num = e.offsetX - 89;
    //   let index = Math.floor((num) / (numall / length));//得到点击的位置    
    //   if (that.xAxis[index]) {
    //     that.$emit("clickFn", {
    //       name: that.xAxis[index],
    //     });
    //   }
    // })

    resizeChart(this.barChart);
  },
};
</script>

<style scoped>
.bar-chart {
  height: 100%;
  width: 100%;
}
</style>
